package com.jihe.ehmall.product.exception;

import com.jihe.common.exception.BizCodeEnume;
import com.jihe.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zyw
 * @version 1.0
 * @date 2021-09-22 16:03
 */
@Slf4j
@RestControllerAdvice
public class EhmallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        Map<String , String> map = new HashMap<>();
        result.getFieldErrors().forEach(error -> {
            map.put(error.getField() , error.getDefaultMessage());
        });

        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(), BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data" , map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R throwableException(Throwable throwable){
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

}
